<template>
  <div class="app-container">
    <!-- 检索 start -->
    <el-filter
      size="medium"
      :data="filterInfo.data"
      :field-list="filterInfo.fieldList"
      :list-type-info="listTypeInfo"
      :show-selection="false"
      @handleFilter="handleFilter"
      @handleReset="handleReset"
      @handleEvent="handleEvent"
    />
    <!-- 检索 end -->

    <!-- 公共操作 star -->
    <fire-oper-menu :show-excel-export="true" :show-excel-import="true" @ExcelExport="handleDownload" @handleCreate="handleCreate" @handleDeleteAll="handleDeleteAll" />
    <!-- 公共操作 end -->

    <!-- 数据列表 start -->
    <fire-table
      ref="table"
      :list="list"
      :total="total"
      :list-loading="listLoading"
      :list-query="filterInfo.data"
      :columns="tableColumns"
      :handle="tableHandle"
      @handleSelectionChange="handleSelectionChange"
    />
    <!-- 数据列表 end -->

    <!-- 提交表单 start -->
    <el-dialog  :close-on-click-modal="false" 
 width="80%" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <ele-form ref="form" v-model="formData" v-bind="formConfig" :request-fn="handleRequest" @request-success="handleRequestSuccess" />
    </el-dialog>
    <!-- 提交表单 end -->

    <!-- 授权表单 start -->
    <el-dialog  :close-on-click-modal="false" 
 width="80%" :title="permissionTitle" :visible.sync="dialogAuthVisible">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="权限" name="permission">
          <div style="text-align: center">
            <el-transfer
              :value="permissionValue[activeName]"
              style="text-align: left; display: inline-block"
              filterable
              :left-default-checked="[2, 3]"
              :right-default-checked="[1]"
              :titles="['未分配', '已分配']"
              :button-texts="['到左边', '到右边']"
              :format="{
                noChecked: '${total}',
                hasChecked: '${checked}/${total}'
              }"
              :data="permissionData[activeName]"
              @change="handleChange"
            />
          </div>
        </el-tab-pane>
        <el-tab-pane label="路由" name="route">
          <div style="text-align: center">
            <el-transfer
              :value="permissionValue[activeName]"
              style="text-align: left; display: inline-block"
              filterable
              :left-default-checked="[2, 3]"
              :right-default-checked="[1]"
              :titles="['未分配', '已分配']"
              :button-texts="['到左边', '到右边']"
              :format="{
                noChecked: '${total}',
                hasChecked: '${checked}/${total}'
              }"
              :data="permissionData[activeName]"
              @change="handleChange"
            />
          </div>
        </el-tab-pane>
        <el-tab-pane label="规则" name="role">规则</el-tab-pane>
      </el-tabs>
    </el-dialog>
    <!-- 授权表单 end -->
  </div>
</template>

<script>
import { fetchList, createPermission,
  updatePermission, deletePermission, getRules, fetchLevels,
  fetchAddons, fetchView, fetchAssign, fetchRemove } from 'diandi-admin/lib/api/admin/permission.js'
// import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
export default {
  data() {
    return {
      // 表格数据 start
      tableColumns: [
        { label: '名称', prop: 'name' },
        {
          label: '权限种类',
          prop: 'type',
          width: 80,
          align: 'center',
          render: (h, { row }) => {
            return h('el-tag', { attrs: { type: row.type === 0 ? '系统' : '模块', size: 'small' }}, row.type === 0 ? '系统' : row.addons)
          }
        },
        {
          label: '权限类型',
          prop: 'permission_type',
          width: 80,
          align: 'center',
          render: (h, { row }) => {
            const permission_types = ['目录', '页面', '按钮', '接口']
            return h('el-tag', {}, permission_types[row.permission_type])
          }
        },
        { label: '规则名称', prop: 'rule_name' },
        { label: '描述', prop: 'description' }
      ],
      tableHandle: [
        {
          label: '修改',
          type: 'primary',
          isPop: false,
          method: row => {
            this.editItem(row)
          }
        },
        {
          label: '删除',
          type: 'danger',
          isPop: true,
          method: row => {
            this.deleteItem(row)
          }
        },
        {
          label: '权限项',
          type: 'warning',
          isPop: false,
          method: row => {
            this.authItem(row)
          }
        }
      ],
      // 表格数据end
      // 检索 start
      filterInfo: {
        data: {
          page: 1,
          limit: 20,
          name: '',
          parent_id: '',
          description: ''
          // sex: 1,
          // date: null,
          // dateTime: null,
          // range: null
        },
        fieldList: [
          { label: '模块类型', type: 'select', value: 'AuthItemSearch[module_name]', list: 'addonsList' },
          { label: '权限名称', type: 'input', value: 'AuthItemSearch[name]' },
          { label: '父级名称', type: 'input', value: 'AuthItemSearch[parent_id]', disabled: true },
          { label: '权限描述', type: 'input', value: 'AuthItemSearch[description]', min: 1, max: 10 }
        ]
      },
      listTypeInfo: {
        addonsList: this.initListTypeInfo()
      },
      // 检索 end
      tableKey: 0,
      formInline: {
        user: '',
        region: ''
      },
      // 表单数据 start
      formData: {},
      formConfig: {
        formDesc: {
          permission_type: {
            type: 'radio',
            label: '权限类型',
            options: [{ text: '目录', value: 0 }, { text: '页面', value: 1 }, { text: '按钮', value: 2 }, { text: '接口', value: 3 }]
          },
          name: {
            type: 'input',
            label: '名称'
          },
          type: {
            type: 'radio',
            label: '权限所属',
            options: [{ text: '系统', value: 0 }, { text: '插件', value: 1 }]
          },
          module_name: {
            type: 'select',
            label: '模块名称',
            isOptions: true,
            vif: data => data.type,
            // 这里必须制定 optionsLinkageFields 做为关联字段，当次字段值发生变化时，会重新出发请求
            optionsLinkageFields: ['type'],
            options: this.initAddons()
          },
          rule_name: {
            type: 'select',
            label: '规则名称',
            isOptions: true,
            options: getRules().then(res => {
              return res.data
            })
          },
          parent_id: {
            type: 'tree-select',
            label: '父级权限',
            isOptions: true,
            options: fetchLevels().then(res => {
              const arr = [{ id: 0, label: '选择父级权限' }]
              return arr.concat(res.data)
            }),
            attrs: {
              showAllLevels: false
            }
          },
          // routes: {
          //   type: 'tree-select',
          //   label: '菜单路由',
          //   isOptions: true,
          //   options: fetchRoute().then(res => {
          //     return res.data;
          //   }),
          //   attrs: {
          //     multiple: true,
          //     clearable: true
          //   }
          // },
          description: {
            type: 'textarea',
            label: '描述',
            attrs: {
              autosizeType: 'switch',
              autosize: false
            }
          },
          data: {
            type: 'textarea',
            label: '数据',
            attrs: {
              autosizeType: 'switch',
              autosize: false
            }
          }
        },
        order: ['permission_type', 'type', 'module_name', 'name', 'rule_name', 'parent_id', 'description', 'data']
      },
      // 表单数据 end
      total: 0,
      list: [],
      demo: {
        title: ''
      },
      temp: {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        type: '',
        status: 'published'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑权限',
        create: '添加权限'
      },
      dialogPvVisible: false,
      pvData: [],
      downloadLoading: false,
      // 权限项管理
      permissionId: 0,
      activeName: 'route', // 0:route,1:permission,2:role
      dialogAuthVisible: false,
      permissionValue: {
        route: [],
        permission: [],
        role: []
      },
      permissionData: {
        route: [],
        permission: [],
        role: []
      },
      permissionTitle: ''
    }
  },
  created() {
    this.getList()
  },
  methods: {
    initAddons() {
      const arr = []
      arr.push({
        text: '选择模块',
        value: ''
      })
      fetchAddons().then(res => {
        const keys = Object.keys(res.data)
        const values = Object.values(res.data)
        values.forEach((item, index) => {
          arr.push({
            text: item,
            value: keys[index]
          })
        })
        console.log('全新', arr)
      })
      console.log('全新', arr)
      return arr
    },
    handleChange(value, direction, movedKeys) {
      const that = this
      console.log(value, direction, movedKeys)
      if (direction === 'right') {
        const ob = {}
        that.$set(ob, that.activeName, movedKeys)
        fetchAssign(that.permissionId, {
          items: ob
        }).then(res => {
          console.log(res)
          that.authItem({
            id: that.permissionId,
            name: that.permissionTitle
          })
        })
      } else {
        const ob = {}
        that.$set(ob, that.activeName, movedKeys)
        fetchRemove(that.permissionId, {
          items: ob
        }).then(res => {
          console.log(res)
          that.authItem({
            id: that.permissionId,
            name: that.permissionTitle
          })
        })
      }
    },
    initListTypeInfo() {
      const arr = []
      arr.push({ id: ' ', name: '选择模块' })
      fetchAddons().then(res => {
        const keys = Object.keys(res.data)
        const values = Object.values(res.data)
        values.forEach((item, index) => {
          arr.push({ id: keys[index], name: item })
        })
      })

      return arr
    },
    // 触发请求
    async resetForm() {
      console.log(this.$refs.form.resetForm())
      await this.$refs.form.resetForm()
    },
    handleSelectionChange(val) {
      console.log('传递来的', val)
    },
    // 更新，和创建
    handleRequest(data) {
      console.log(data)
      const that = this

      if (that.dialogStatus === 'create') {
        if (data.type === 0) {
          data.module_name = 'sys'
        }

        createPermission(data).then(response => {
          console.log(response)
          that.getList()
          that.dialogFormVisible = false
        })
      } else if (that.dialogStatus === 'update') {
        updatePermission(data).then(res => {
          console.log('更新', res)
          that.getList()
          that.dialogFormVisible = false
        })
      }

      return Promise.resolve()
    },
    // 单行数据删除
    deleteItem(row) {
      const that = this
      deletePermission(row.id).then(res => {
        console.log('更新', res)
        that.getList()
        that.dialogFormVisible = false
      })
    },
    handleClick(tab, event) {
      const that = this
      console.log('permissionData', that.permissionData, that.activeName)
      console.log('handleClick', tab, event, that.activeName, that.permissionData[that.activeName])
      // that.activeName = tab
    },
    authItem(row) {
      const that = this
      that.dialogAuthVisible = true
      that.permissionId = row.id
      that.permissionTitle = row.name

      fetchView(row.id).then(res => {
        console.log('assigneds', res.data.assignedKey)
        that.permissionData = res.data.availables
        that.permissionValue = res.data.assignedKey
      })
    },
    handleRequestSuccess() {
      this.$message.success('发送成功')
    },
    getList() {
      const that = this
      that.listLoading = true
      fetchList(that.filterInfo.data).then(response => {
        console.log('response', response)
        that.total = response.data.dataProvider.total
        that.list = response.data.list
        console.log('列表数据层级测试', that.list)
        that.listLoading = false
      })
    },
    /** 搜索 */
    handleFilter(row) {
      const that = this
      console.log(row)
      that.$set(that.filterInfo, 'data', row)
      console.log('检索前', that.filterInfo.data)
      that.getList()
    },
    /** 重置 */
    handleReset(row) {
      console.log(row)
    },
    /** 焦点失去事件 */
    handleEvent(row) {
      console.log(row)
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    handleCreate() {
      const that = this
      this.resetForm()
      console.log(this.list)
      that.dialogStatus = 'create'
      that.dialogFormVisible = true
    },
    handleDeleteAll() {
      console.log('删除')
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
    },
    updateData() {},
    handleDelete(row, index) {
      this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000
      })
      this.list.splice(index, 1)
    },
    editItem(row) {
      const that = this
      that.formData = { ...row }
      that.dialogFormVisible = true
      console.log('formData', row, that.formData)
      this.dialogStatus = 'update'
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['title', 'create_time']
        const filterVal = [{ title: '12', create_time: '23435345353' }]
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v =>
        filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
<style>
  .el-transfer-panel{
    width: 300px;
  }
</style>
